package com.example.goodog.activities;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.example.android.wizardpager.AbstractWizardModel;
import com.example.android.wizardpager.AddDogWizardModel;
import com.example.android.wizardpager.SignOnWizardModel;
import com.example.goodog.AddDogResponse;
import com.example.goodog.ExpandAnimation;
import com.example.goodog.LoginManager;
import com.example.goodog.MyApplication;
import com.example.goodog.R;
import com.example.goodog.adapters.UserDogAdapter;
import com.example.goodog.interfaces.LoggedinCallback;
import com.google.gson.Gson;

/**
 * Activity which displays a login screen to the user, offering registration as
 * well.
 */
public class UserActivity extends Activity {
	
	public static final int CHANGE_DOGS_LOCATION = 3;
	public static final int CHANGE_DOG_LOCATION = 5;
	
	public static final int REGISTER_WIZARD = 99;
	public static final int ADD_DOG_WIZARD = 98;
	public static final int EDIT_DOG_WIZARD = 97;

	

	


	private LoginManager loginManager;


	// Values for email and password at the time of the login attempt.
	private String mEmail;
	private String mPassword;

	// UI references.
	private EditText mEmailView;
	private EditText mPasswordView;
	private View mLoginFormView;
	private View mLogoutFormView;
	private ListView listView;
	private Context context = this;
	private UserDogAdapter adapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_user);

		loginManager = new LoginManager();
		loginManager.callback = new LoggedinCallback() {

			@Override
			public void loggedInCall() {
				MyApplication.setUser(loginManager.getUser(),loginManager.getPassword(),context);


				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						MyApplication.UpdateDogsLocation(context,null,null,false);
					}
				});


			}

			@Override
			public void loggedOutCall() {
				MyApplication.setUser(null,context);
			}

			@Override
			public void AfterTheAttempt() {
				/*Intent resultIntent = new Intent();
				setResult(Activity.RESULT_OK, resultIntent);
				finish();*/
				RefreshForms();
			}
		};
		mEmailView = (EditText) findViewById(R.id.email);
		mEmailView.setText(mEmail);

		mPasswordView = (EditText) findViewById(R.id.password);
		mPasswordView
		.setOnEditorActionListener(new TextView.OnEditorActionListener() {
			@Override
			public boolean onEditorAction(TextView textView, int id,
					KeyEvent keyEvent) {
				if (id == R.id.login || id == EditorInfo.IME_NULL) {
					attemptLogin();
					return true;
				}
				return false;
			}
		});

		mLoginFormView = findViewById(R.id.login_form);
		mLogoutFormView = findViewById(R.id.logout_form);
		RefreshForms();

		findViewById(R.id.sign_in_button).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						attemptLogin();
					}
				});

		findViewById(R.id.resister_button).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						Register();
					}
				});

		findViewById(R.id.sign_out_button).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						LogOut();
					}
				});
		
		findViewById(R.id.change_dog_location_button).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						ChangeDogsLocation();
					}
				});

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		getMenuInflater().inflate(R.menu.login, menu);
		return true;
	}

	public void Register()
	{
		Intent intent = new Intent(this, WizardActivity.class);
		intent.putExtra("wizard", REGISTER_WIZARD);
		startActivityForResult(intent, WizardActivity.REGISTER);
	}

	public void AddDog(View v)
	{
		Intent intent = new Intent(this, WizardActivity.class);
		intent.putExtra("wizard", ADD_DOG_WIZARD);
		startActivityForResult(intent, WizardActivity.ADD_DOG);
	}
	
	public void ChangeDogsLocation()
	{
		Intent intent = new Intent(this, ChangeLocationActivity.class);
		startActivityForResult(intent, CHANGE_DOGS_LOCATION);
	}

	/**
	 * Attempts to sign in or register the account specified by the login form.
	 * If there are form errors (invalid email, missing fields, etc.), the
	 * errors are presented and no actual login attempt is made.
	 */
	public void attemptLogin() {
		// Reset errors.
		mEmailView.setError(null);
		mPasswordView.setError(null);

		// Store values at the time of the login attempt.
		mEmail = mEmailView.getText().toString();
		mPassword = mPasswordView.getText().toString();

		boolean cancel = false;
		View focusView = null;

		// Check for a valid password.
		if (TextUtils.isEmpty(mPassword)) {
			mPasswordView.setError(getString(R.string.error_field_required));
			focusView = mPasswordView;
			cancel = true;
		} else if (mPassword.length() < 4) {
			mPasswordView.setError(getString(R.string.error_invalid_password));
			focusView = mPasswordView;
			cancel = true;
		}

		// Check for a valid email address.
		if (TextUtils.isEmpty(mEmail)) {
			mEmailView.setError(getString(R.string.error_field_required));
			focusView = mEmailView;
			cancel = true;
		} else if (!mEmail.contains("@")) {
			mEmailView.setError(getString(R.string.error_invalid_email));
			focusView = mEmailView;
			cancel = true;
		}

		if (cancel) {
			// There was an error; don't attempt login and focus the first
			// form field with an error.
			focusView.requestFocus();
		} else {
			LogInByMailAndPassword( mEmailView.getText().toString(),mPasswordView.getText().toString());
		}
	}

	public void LogInByMailAndPassword(String Mail, String Password) {
		// Show a progress spinner, and kick off a background task to
		// perform the user login attempt.
		loginManager.setMail(Mail);
		loginManager.setPassword(Password);

		loginManager.StartLogingIn();
	}

	public void LogOut() {
		// Show a progress spinner, and kick off a background task to
		// perform the user login attempt.
		loginManager.LogOut();
	}



	public static AbstractWizardModel GetLoginWizard(Context c) {
		return new SignOnWizardModel(c);
	}

	public static AbstractWizardModel GetAddDogWizard(Context c) {
		return new AddDogWizardModel(c);
	}
	
	


	

	public void RefreshForms() {

		UserActivity.this.runOnUiThread(new Runnable() {

			@Override
			public void run() {
				if(MyApplication.getUser()==null)
				{	
					mLoginFormView.setVisibility(View.VISIBLE);
					mLogoutFormView.setVisibility(View.GONE);
					listView = (ListView) findViewById(R.id.listView_userDogs);
					listView = new ListView(context);
				}
				else
				{
					mLoginFormView.setVisibility(View.GONE);
					mLogoutFormView.setVisibility(View.VISIBLE);
					listView = (ListView) findViewById(R.id.listView_userDogs);
					
					if(adapter == null)
					{
						adapter = new UserDogAdapter(context,R.layout.dog_item);
					}
					listView.setAdapter(adapter);
					SetToolBarAnimationOnClick(listView);
				}
			}
		});


	}
	
	public void SetToolBarAnimationOnClick(ListView listView) {
		// Creating an item click listener, to open/close our toolbar for each item
		listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {

				View toolbar = view.findViewById(R.id.toolbar);

				// Creating the expand animation for the item
				ExpandAnimation expandAni = new ExpandAnimation(toolbar, 500);

				// Start the animation on the toolbar
				toolbar.startAnimation(expandAni);
			}
		});
	}

	
	@Override 
	public void onActivityResult(int requestCode, int resultCode, Intent data) {     
		super.onActivityResult(requestCode, resultCode, data); 
		switch(requestCode) { 
		case (WizardActivity.REGISTER) : { 
			if (resultCode == Activity.RESULT_OK) { 
				Bundle extras = data.getExtras();
				if(extras != null)
				{
					String Mail = extras.getString("Mail",null);
					String Password = extras.getString("Password",null);
					LogInByMailAndPassword(Mail, Password);
				}
			} 
			break; 
		} 

		case (WizardActivity.ADD_DOG) : { 
			if (resultCode == Activity.RESULT_OK) { 
				Bundle extras = data.getExtras();
				if(extras != null)
				{
					String response = extras.getString("JsonResponseFromServer","BAD");
					if(!response.equals("BAD"))
					{
						Gson gson = new Gson(); 
						AddDogResponse adr = gson.fromJson(response, AddDogResponse.class);
						adr.Dog.ImageBlob = adr.Image;
						MyApplication.getUser().Dogs.add(adr.Dog);
						adapter.notifyDataSetChanged();
					}
				}
			} 
			break; 
		}
		
		case (WizardActivity.EDIT_DOG) : { 
			if (resultCode == Activity.RESULT_OK) { 
				Bundle extras = data.getExtras();
				if(extras != null)
				{
					String response = extras.getString("JsonResponseFromServer","BAD");
					if(!response.equals("BAD"))
					{
						Gson gson = new Gson(); 
						AddDogResponse adr = gson.fromJson(response, AddDogResponse.class);
						adr.Dog.ImageBlob = adr.Image;
						MyApplication.getUser().Dogs.set(MyApplication.getUser().Dogs.indexOf(adr.Dog),adr.Dog);
						adapter.notifyDataSetChanged();
					}
				}
			} 
			break; 
		}
		
		case (CHANGE_DOGS_LOCATION) : { 
			if (resultCode == Activity.RESULT_OK) { 
				final Address address = data.getParcelableExtra(ChangeLocationActivity.Address);
				if(address != null)
				{
					runOnUiThread(new Runnable() {

						@Override
						public void run() {
							MyApplication.UpdateDogsLocation(context, address,null,false);
						}
					});
				}
				String LocationMethod = data.getStringExtra(ChangeLocationActivity.LocationMethod);
			} 
			break; 
		}
		case (CHANGE_DOG_LOCATION) : { 
			if (resultCode == Activity.RESULT_OK) { 
				final Address address = data.getParcelableExtra(ChangeLocationActivity.Address);
				final long DogID = data.getLongExtra("dog_ID", 0);
				
				if(address != null)
				{
					runOnUiThread(new Runnable() {

						@Override
						public void run() {
							ArrayList<Long> DogsIDs = new ArrayList<Long>();
							DogsIDs.add(DogID);
							MyApplication.UpdateDogsLocation(context, address,DogsIDs,true);
						}
					});
				}
				String LocationMethod = data.getStringExtra(ChangeLocationActivity.LocationMethod);
			} 
			break; 
		}
		

		} 
	}
	
	
	
	

}

